﻿using Infrastructure.Extension;
using Microsoft.EntityFrameworkCore;

namespace Application.Service
{
    public class SettingService : ISettingService
    {
        public JobManagerDbContext _context { get; set; }
        public SettingService(JobManagerDbContext DbContext)
        {
            _context = DbContext;
        }
        public async Task<List<KeyValue>> Get(SettingRequest request)
        {
            request.StringTrim();
            var data = await _context.KeyValue.AsQueryable()
                .WhereIf(request.Type != null, s => s.Type == request.Type)
                .ToListAsync();
            return data;
        }
        public async Task Save(List<KeyValue> request)
        {
            var keys = request.Select(s => s.Key);
            var list = await _context.KeyValue.Where(s => keys.Contains(s.Key)).ToListAsync();

            foreach (var item in request)
            {
                var data = list.FirstOrDefault(s => s.Key == item.Key);
                if (data == null)
                {
                    var entity = new KeyValue
                    {
                        Key = item.Key,
                        Value = item.Value,
                        Type = item.Type
                    };
                    await _context.KeyValue.AddAsync(entity);
                }
                else
                {
                    data.Value = item.Value;
                }
            }
            await _context.SaveChangesAsync();
        }
        public async Task<List<ServiceResponse>> GetService()
        {
            var datas = await _context.KeyValue.Where(s => s.Type == KeyValueType.Server).ToListAsync();
            return datas.Select(s => new ServiceResponse
            {
                CreateTime = s.CreateTime,
                UpdateTime = s.UpdateTime.TimeElapsed(TimeScale.min),
                ServerId = s.Id,
                ServerKey = s.Key,
                Status = GetStatus(s.UpdateTime),
                Value = s.Value
            }).ToList();

            string GetStatus(DateTime dateTime)
            {
                var status = "正常";
                if (dateTime <= DateTime.Now.AddSeconds(-60)) status = "服务检测异常";
                if (dateTime <= DateTime.Now.AddSeconds(-12)) status = "服务异常(即将被剔除)";
                return status;
            }
        }
    }

    public interface ISettingService
    {
        Task<List<KeyValue>> Get(SettingRequest request);
        Task Save(List<KeyValue> request);
        Task<List<ServiceResponse>> GetService();
    }
}
